﻿using System;
using System.ComponentModel.Composition;
using System.Linq;
using System.Windows.Input;
using Security.Domain;
using Security.Events;
using Security.Events.Commands;
using Security.Helpers;
using Security.Specs.DataLayer;
using Security.Specs.Implementation.Common;
using Security.Specs.Reports;
using Security.Specs.Services;

namespace Security.Specs.Implementation.NodeRoots
{
    [Export(typeof(SecurityNodeReportBase)), SecurityNodeRootMetadata(typeof(Employee),(int) SecurityRootNodeOrder.Employees)]
    public class EmployeeSecurityNodeRoot : SecurityNodeReport
    {
        private readonly EventBroker eventBroker;
        private readonly ISecurityDataModel model;
        private readonly IEmployeeService employeeService;

        [ImportingConstructor]
        public EmployeeSecurityNodeRoot(EventBroker eventBroker, ISecurityDataModel model, IEmployeeService employeeService) :
            base(Strings.GetRootNodeDescription(typeof(Employee)), typeof(Employee))
        {
            this.eventBroker = eventBroker;
            this.model = model;
            this.employeeService = employeeService;

            nodes.Add(Empty());

            Subscribe();
        }

        private void Subscribe()
        {
            eventBroker.OfType<ChangesCommittedCommand>().
                Where(c => c.Type.IsBaseOf(typeof(Employee))).
                Subscribe(OnChangeCommited);
        }

        private void OnChangeCommited(ChangesCommittedCommand command)
        {
            ChildNodesCollectionNeeded();
        }

        protected override void ChildNodesCollectionNeeded()
        {
                nodes.Clear();
                foreach (var employee in model.Employees.OrderBy(e => e.Lastname).ToArray())
                {
                    nodes.Add(new SecurityNodeReport(employeeService.FormatEmployee(employee), employee));
                }
        }
    }
}